//
//  UITextField+limitLength.m
//  playcar
//
//  Created by yqh on 2018/3/30.
//  Copyright © 2018年 ljkj. All rights reserved.
//

#import "UITextField+limitLength.h"
#import <objc/runtime.h>

@implementation UITextField (limitLength)

static const void *FCKey_IsObserver_TextDidChange   = &FCKey_IsObserver_TextDidChange;

static const void *FCKey_MaxInputLength     = &FCKey_MaxInputLength;

static const void *FCKey_AllowsHanziOnly    = &FCKey_AllowsHanziOnly;


- (BOOL)isObserver_TextDidChange {
    return [objc_getAssociatedObject(self, FCKey_IsObserver_TextDidChange) boolValue];
}
- (void)setIsObserver_TextDidChange:(BOOL)isObserver_TextDidChange {
    objc_setAssociatedObject(self, FCKey_IsObserver_TextDidChange, [NSNumber numberWithBool:isObserver_TextDidChange], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSInteger)maxLength {
    return [objc_getAssociatedObject(self, FCKey_MaxInputLength) integerValue];
}
- (void)setMaxLength:(NSInteger)maxLength {
    if (maxLength == 0) {
        maxLength = NSIntegerMax;
    }
    objc_setAssociatedObject(self, FCKey_MaxInputLength, [NSNumber numberWithInteger:maxLength], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [self addNotification_textDidChange];
}
- (void)limitTextLength:(int)length {
    self.maxLength = length;
}

- (BOOL)allows_Hanzi_only {
    return [objc_getAssociatedObject(self, FCKey_AllowsHanziOnly) boolValue];
}
- (void)setAllows_Hanzi_only:(BOOL)allows_Hanzi_only {
    objc_setAssociatedObject(self, FCKey_AllowsHanziOnly, [NSNumber numberWithBool:allows_Hanzi_only], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [self addNotification_textDidChange];
}

- (void (^)(NSString *, NSInteger, NSInteger))textDidChangeBlock {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setTextDidChangeBlock:(void (^)(NSString *, NSInteger, NSInteger))textDidChangeBlock {
    objc_setAssociatedObject(self, @selector(textDidChangeBlock), textDidChangeBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(UITextField *))didClickReturnKey {
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setDidClickReturnKey:(void (^)(UITextField *))didClickReturnKey {
    objc_setAssociatedObject(self, @selector(didClickReturnKey), didClickReturnKey, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)addNotification_textDidChange {
    if (self.isObserver_TextDidChange == NO) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify_textDidChange:) name:UITextFieldTextDidChangeNotification object:self];
        self.isObserver_TextDidChange = YES;
    }
}
- (void)removeNotification_textDidChange {
    if (self.isObserver_TextDidChange) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self];
        self.isObserver_TextDidChange = NO;
    }
}

- (void)disposeRelated {
    self.textDidChangeBlock = nil;
    [self removeNotification_textDidChange];
    objc_removeAssociatedObjects(self);
}
- (void)dealloc {
    @try {
        [self removeNotification_textDidChange];
    }
    @catch (NSException *exception) {
        
    }
}





- (void)notify_textDidChange:(NSNotification *)notify {
    
    UITextField *textField = (UITextField *)notify.object;
    
    if (textField == self) {
        
        NSInteger maxLength     = self.maxLength;
        BOOL allowsOnlyHanzi    = self.allows_Hanzi_only;
        
        if (maxLength == 0 && allowsOnlyHanzi == NO) {
            return;
        }
        
        //只能输入汉字
        if (allowsOnlyHanzi) {
            
            UITextRange *selectedRange = self.markedTextRange;
            UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
            
            if (!position) {
                
                NSString *text = [self filterCharactor:self.text withRegex:@"[^\u4e00-\u9fa5]"];
                
                //限制长度
                if (maxLength > 0) {
                    if (text.length > maxLength) {
                        text = [text substringToIndex:maxLength];
                    }
                }
                
                self.text = text;
            }
            
        } else {
            
            NSString *toBeString = self.text;
            NSString *lang = [[self textInputMode] primaryLanguage]; // 键盘输入模式
            
            if ([lang isEqualToString:@"zh-Hans"]) {
                
                //简体中文输入，包括简体拼音，健体五笔，简体手写
                UITextRange *selectedRange = [self markedTextRange];
                //获取高亮部分
                UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
                //没有高亮选择的字，则对已输入的文字进行字数统计和限制
                if (!position) {
                    if (toBeString.length > maxLength) {
                        self.text = [toBeString substringToIndex:maxLength];
                    }
                }
                //有高亮选择的字符串，则暂不对文字进行统计和限制
                else {
                    
                }
            }
            //中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
            else {
                if (toBeString.length > maxLength) {
                    self.text = [toBeString substringToIndex:maxLength];
                }
            }
        }
        
        
        //回调
        if (self.textDidChangeBlock) {
            self.textDidChangeBlock(textField.text, maxLength, self.text.length);
        }
    }
}

//过滤指定字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr {
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}

@end
